#include "main.h"

// PWM control for RGB LED
PwmOut led_r(PB_11);
PwmOut led_g(PB_1);
PwmOut led_b(PB_15);

// Digital control for 4 single-color LEDs
DigitalOut LED_1(PB_8);
DigitalOut LED_2(PB_4);
DigitalOut LED_3(PC_9);
DigitalOut LED_4(PC_10);

// RGB LED control
uint8_t rgb_state = 0;

void rgb_led() {
    if (!role_heat_flag) return; // Only active when player is heated

    if (rgb_time == 400) rgb_state++;
    if (rgb_state > 3) rgb_state = 1;

    if (rgb_state == 1) {
        led_g.period_us(1000);
        led_g.pulsewidth_us(500);
    }
    else if (rgb_state == 2) {
        led_r.period_us(1000);
        led_r.pulsewidth_us(500);
    }
    else if (rgb_state == 3) {
        led_b.period_us(1000);
        led_b.pulsewidth_us(500);
    }
    else {
        led_r = 0;
        led_g = 0;
        led_b = 0;
    }
}

void rgb_init() {
    // Initialize RGB LED with default brightness
    led_g.period_ms(20);
    led_g.pulsewidth_ms(10);
    led_r.period_ms(20);
    led_r.pulsewidth_ms(10);
}

// LED control for boot, death, etc.
uint8_t led_boot_flag = 1;
uint8_t led_state = 0;
uint8_t led_last_state = 0;

void led_show() {
    if (led_slow) return;
    led_slow = 1;

    if (led_last_state == led_state) return;

    // Update 4 LEDs based on led_state
    LED_1 = (led_state & 0x01) > 0;
    LED_2 = (led_state & 0x02) > 0;
    LED_3 = (led_state & 0x04) > 0;
    LED_4 = (led_state & 0x08) > 0;

    led_last_state = led_state;
}

void led_show_change(uint8_t pos, uint8_t state) {
    if (pos < 1 || pos > 4) return;
    if (state == 1) {
        led_state |= (1 << (pos - 1));  // Turn on
    } else {
        led_state &= ~(1 << (pos - 1)); // Turn off
    }
}

uint8_t led_boot_pos = 0;

void boot_led_show() {
    if (led_boot_flag == 1) {
        led_boot_flag = 2;
        led_flag_ms = 0;
        led_boot_pos = 0;
    }
    if (led_boot_flag == 2) {
        if (led_flag_ms / 800 == 1) {
            led_boot_pos++;
            led_show_change(led_boot_pos, 1); // Turn on LEDs one by one
            if (led_boot_pos == 4) {
                led_boot_pos = 0;
                led_boot_flag = 0;
            }
            led_flag_ms = 0;
        }
    }
}

uint8_t death_led_state = 0;

void death_led_show() {
    if (role_health == 0) {
        if (led_flag_ms >= 250) {
            death_led_state = 1 - death_led_state;
            led_show_change(1, death_led_state); // Blink LED when player is dead
            led_flag_ms = 0;
        }
    }
}

void led_main_show() {
    death_led_show();
    boot_led_show();
    led_show();
}
